package com.niiwoo.civet.trade.service.local.contract;

import com.alibaba.dubbo.config.annotation.Reference;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.entity.ProjectInvestOrder;
import com.niiwoo.civet.trade.dao.entity.ProjectPackageInvestOrder;
import com.niiwoo.civet.trade.dao.mapper.ProjectInvestOrderMapperExt;
import com.niiwoo.civet.trade.dao.mapper.ProjectMapperExt;
import com.niiwoo.civet.trade.service.local.contract.vo.BorrowerContractDTO;
import com.niiwoo.civet.trade.service.local.contract.vo.IntelligentContractDTO;
import com.niiwoo.civet.trade.service.local.contract.vo.InvestorContractDTO;
import com.niiwoo.civet.user.dto.request.SimpleOrgInfo;
import com.niiwoo.civet.user.dto.response.UserAuthorizationInfoResponseDTO;
import com.niiwoo.civet.user.dto.response.UserIdentityInfoResponseDTO;
import com.niiwoo.civet.user.service.OrganizationDubboService;
import com.niiwoo.civet.user.service.UserAuthorizationInfoDubboService;
import com.niiwoo.civet.user.service.UserIdentityDubboService;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import com.niiwoo.tripod.provider.exception.BizException;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class ContractBaseService {
	
	@Reference(version = "1.0.0")
	private UserIdentityDubboService userIdentityDubboService;

	@Reference(version = "1.0.0")
	private UserAuthorizationInfoDubboService userAuthorizationInfoDubboService;
	
	@Reference(version = "1.0.0")
	private OrganizationDubboService organizationDubboService;

	@Autowired
	private ProjectInvestOrderMapperExt projectInvestOrderMapperExt;
	
	@Autowired
	private ProjectMapperExt projectMapperExt;

	@Autowired
	private SnowflakeIdWorker snowflakeIdWorker;
	
	@Autowired
    private PrivacyMasks privacyMasks;
	
	/**
	 * 获取指定标的签订合同书时所需的所有投资人信息
	 * @param projectId
	 * @return
	 */
	public List<InvestorContractDTO> getInvestUserInfo(Long projectId) {
		List<ProjectInvestOrder> list = projectInvestOrderMapperExt.selectInvestSuccessList(projectId);
		List<InvestorContractDTO> result = new ArrayList<InvestorContractDTO>();
		
		if (list == null || list.isEmpty()) return result;
		
		InvestorContractDTO dto = null;
		Set<String> userIdSet = new HashSet<>();
		Set<String> orgIdSet = new HashSet<>();
		
		for (ProjectInvestOrder investOrder : list) {
			if (investOrder.getInvestorType() == 1) //个人
				userIdSet.add(investOrder.getUserId());
			else
				orgIdSet.add(investOrder.getUserId());
		}
		
		Map<String, UserIdentityInfoResponseDTO> userIdentityInfoMap = new HashMap<>();
		if (!userIdSet.isEmpty()) {
			List<UserIdentityInfoResponseDTO> userIdentityInfoList = userIdentityDubboService.queryUserIdentityListByUserIdSet(userIdSet);
			for (UserIdentityInfoResponseDTO userIdentityInfo : userIdentityInfoList) {
				userIdentityInfoMap.put(userIdentityInfo.getUserId(), userIdentityInfo);
			}
		}
		
		Map<String, SimpleOrgInfo> orgMap = new HashMap<>();
    	if (!orgIdSet.isEmpty()) {
        	List<SimpleOrgInfo> orgInfoDTOS = organizationDubboService.queryListByOrgIdSet(orgIdSet);
        	for (SimpleOrgInfo org : orgInfoDTOS) {
        		orgMap.put(org.getId(), org);
        	}
    	}
    	
    	Map<String, UserAuthorizationInfoResponseDTO> userAuthorizationMap = new HashMap<>();
		if (!userIdSet.isEmpty()) {
			List<UserAuthorizationInfoResponseDTO> userAuthorizationInfoList = userAuthorizationInfoDubboService
					.queryUserAuthorizationInfoListByUserIdSet(userIdSet);
			if (userAuthorizationInfoList != null) {
				for (UserAuthorizationInfoResponseDTO userAuth : userAuthorizationInfoList) {
					userAuthorizationMap.put(userAuth.getUserId(), userAuth);
				}
			}
		}
		
    	SimpleOrgInfo orgInfo = null; 
		for (ProjectInvestOrder investOrder : list) {
			dto = new InvestorContractDTO();
			
			dto.setInvestUserId(investOrder.getUserId());
			dto.setInvestAmount(investOrder.getAmount());
			
			if (investOrder.getInvestorType() == 1) { //个人
				if (userIdentityInfoMap.get(dto.getInvestUserId()) == null) continue;
				
				dto.setInvestorType((byte) 1);
				dto.setInvestorIdCard(userIdentityInfoMap.get(dto.getInvestUserId()).getIdCard());
				dto.setInvestUserName(userIdentityInfoMap.get(dto.getInvestUserId()).getName());
				dto.setFadadaCacertId(userAuthorizationMap.get(dto.getInvestUserId()).getFadadaCacertId());
			} else { //企业
				orgInfo = orgMap.get(dto.getInvestUserId());
				if (orgInfo == null) continue;
				
				dto.setInvestorType((byte) 2);
				dto.setInvestorIdCard(StringUtils.isBlank(orgInfo.getUnifiedSocialCreditCode())
								? orgInfo.getCharterCode()
								: orgInfo.getUnifiedSocialCreditCode()); // 统一社会信用代码，如果统一社会信用代码为空则取用营业执照编号
				dto.setInvestUserName(orgInfo.getOrganizationName());
				dto.setFadadaCacertId(orgInfo.getFadadaCacertId());
			}
			
			result.add(dto);
		}
		
		return result;
	}
	
	/**
	 * 查询对应借款用户信息
	 * @param projectId
	 * @return
	 */
	public BorrowerContractDTO getBorrowerContractDTO(Long projectId) {
		Project project = projectMapperExt.selectByPrimaryKey(projectId);
		
		String borrowerUserId = project.getBorrowUserId();
		
		BorrowerContractDTO result = null;
		if (project.getBorrowerType() == 1) { // 个人
			UserIdentityInfoResponseDTO userIdentityInfoResponseDTO = userIdentityDubboService.get(borrowerUserId);
			if (userIdentityInfoResponseDTO != null) {
				result = new BorrowerContractDTO();
				result.setBorrowAmount(project.getContractAmount());
				result.setBorrowerType(project.getBorrowerType());
				result.setBorrowerIdCard(userIdentityInfoResponseDTO.getIdCard());
				result.setBorrowerUserName(userIdentityInfoResponseDTO.getName());
				result.setBorrowerAddress(userIdentityInfoResponseDTO.getAddress());
				
				UserAuthorizationInfoResponseDTO userAuthorizationInfoResponseDTO = userAuthorizationInfoDubboService.getUserAuthorizationInfo(borrowerUserId);
				if (userAuthorizationInfoResponseDTO != null)
					result.setFadadaCacertId(userAuthorizationInfoResponseDTO.getFadadaCacertId());
			}
		} else { //企业
			SimpleOrgInfo orgInfo = organizationDubboService.getByOrgId(borrowerUserId);
			if (orgInfo != null) {
				result = new BorrowerContractDTO();
				result.setBorrowAmount(project.getContractAmount());
				result.setBorrowerType(project.getBorrowerType());
				result.setBorrowerIdCard(StringUtils.isBlank(orgInfo.getUnifiedSocialCreditCode())
						? orgInfo.getCharterCode()
						: orgInfo.getUnifiedSocialCreditCode()); // 统一社会信用代码，如果统一社会信用代码为空则取用营业执照编号
				result.setBorrowerUserName(orgInfo.getOrganizationName());
				result.setFadadaCacertId(orgInfo.getFadadaCacertId());
				result.setBorrowerAddress(orgInfo.getAddress());
			}
		}
		
		if (result == null) throw new BizException("USR10028"); //用户不存在
		
		return result;
	}
	
	/**
	 * 预览合同接口获取当前所有投资人信息(用于预览接口)
	 * @param projectId
	 * @return
	 */
	public List<InvestorContractDTO> getInvestUserInfoFromInvestorOrder(Long projectId) {
		List<ProjectInvestOrder> list = projectInvestOrderMapperExt.selectInvestSuccessList(projectId);
		List<InvestorContractDTO> result = new ArrayList<InvestorContractDTO>();
		
		if (list == null || list.isEmpty()) return result;
		
		InvestorContractDTO dto = null;
		Set<String> orgIdSet = new HashSet<>();
		
		SimpleOrgInfo orgInfo = null; 
		for (ProjectInvestOrder investOrder : list) {
			if (investOrder.getInvestorType() == 1) continue; //个人
			else orgIdSet.add(investOrder.getUserId());
		}
		
		Map<String, SimpleOrgInfo> orgMap = new HashMap<>();
    	if (!orgIdSet.isEmpty()) {
        	List<SimpleOrgInfo> orgInfoDTOS = organizationDubboService.queryListByOrgIdSet(orgIdSet);
        	for (SimpleOrgInfo org : orgInfoDTOS) {
        		orgMap.put(org.getId(), org);
        	}
    	}
		
		for (ProjectInvestOrder investOrder : list) {
			dto = new InvestorContractDTO();
			
			dto.setInvestUserId(investOrder.getUserId());
			dto.setInvestAmount(investOrder.getAmount());
			
			if (investOrder.getInvestorType() == 1) { //个人
				dto.setInvestorType((byte) 1);
				dto.setInvestorIdCard(investOrder.getInvestorIdCard());
				dto.setInvestUserName(investOrder.getInvestorName());
			} else { //企业
				orgInfo = orgMap.get(dto.getInvestUserId());
				if (orgInfo == null) continue;
				
				dto.setInvestorType((byte) 2);
				dto.setInvestorIdCard(StringUtils.isBlank(orgInfo.getUnifiedSocialCreditCode())
								? orgInfo.getCharterCode()
								: orgInfo.getUnifiedSocialCreditCode()); // 统一社会信用代码，如果统一社会信用代码为空则取用营业执照编号
				dto.setInvestUserName(orgInfo.getOrganizationName());
				dto.setFadadaCacertId(orgInfo.getFadadaCacertId());
			}
			
			result.add(dto);
		}
		
		return result;
	}
	
	/**
	 * 获取当前用户投资人角色相关合同信息
	 * @param userId
	 * @return
	 */
	public InvestorContractDTO getCurrentUserContractDTO(String userId) {
		InvestorContractDTO dto = null;

		//userIdentityDubboService.get()方式获取到的数中idcard已解码
		UserIdentityInfoResponseDTO userIdentityInfoResponseDTO = userIdentityDubboService.get(userId);
		if (userIdentityInfoResponseDTO != null) {
			dto = new InvestorContractDTO();
			dto.setInvestUserId(userId);
			dto.setInvestorType((byte)1);
			dto.setInvestorIdCard(userIdentityInfoResponseDTO.getIdCard());
			dto.setInvestUserName(userIdentityInfoResponseDTO.getName());
		} else {
			SimpleOrgInfo orgInfo = organizationDubboService.getByOrgId(userId);
			if (orgInfo != null) {
				dto = new InvestorContractDTO();
				dto.setInvestUserId(userId);
				dto.setInvestorType((byte)2);
				dto.setInvestorIdCard(StringUtils.isBlank(orgInfo.getUnifiedSocialCreditCode())
						? orgInfo.getCharterCode()
						: orgInfo.getUnifiedSocialCreditCode()); // 统一社会信用代码，如果统一社会信用代码为空则取用营业执照编号
				dto.setInvestUserName(orgInfo.getOrganizationName());
			}
		}
		
		if (dto == null) throw new BizException("USR10028"); //用户不存在
		
		return dto;
	}
	
	/**
	 * 打码
	 * @param code 需要打码的字符串
	 * @param isCompany 是否公司
	 * @return
	 */
	public String maskCode(String code, boolean isCompany) {
		if (StringUtils.isBlank(code)) return null;
		
		if (isCompany) {
			return privacyMasks.maskInstitutionalReditCode(code);
		} else {
			return maskIdCard(code, true, true);
		}
	}
	
	/**
	 * 打码
	 * @param code 需要打码的字符串
	 * @param isCompany 是否公司
	 * @return
	 */
	public String maskCodeNoMask(String code, boolean isCompany) {
		if (StringUtils.isBlank(code)) return null;
		
		if (isCompany) {
			return code;
		} else {
			return maskIdCard(code, true, false);
		}
	}
	
	/**
	 * 打码
	 * @param code 需要打码的字符串
	 * @param needDecrypt 是否需要先解密
	 * @return
	 */
	private String maskIdCard(String code, boolean needDecrypt, boolean needMask) {
		if (StringUtils.isBlank(code)) return null;
		
		if (needDecrypt) {
			if (!needMask) return privacyMasks.decryptPrivacy(code);
			
			return privacyMasks.maskIdCardSixTwo(privacyMasks.decryptPrivacy(code));
		} else {
			if (!needMask) return code;
			
			return privacyMasks.maskIdCardSixTwo(code);
		}
	}
	
	/**
	 * 名称打码
	 * @param name 需要打码的名称（用户姓名或公司名称）
	 * @return
	 */
	public String maskName(String name) {
		if (StringUtils.isBlank(name)) return null;
		
		StringBuffer buf = new StringBuffer();
		buf.append(name.substring(0, 1));
		buf.append(name.replaceAll(".", "*").substring(1));
		
		return buf.toString();
	}

	/**
	 * 投资人列表排序：甲方一、甲方二
	 * @param index
	 * @return
	 */
	public String toChinese(int index) {
		String string = String.valueOf(index);
		String[] s1 = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
		String[] s2 = { "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千" };

		String result = "";

		int n = string.length();
		for (int i = 0; i < n; i++) {

			int num = string.charAt(i) - '0';

			if (i != n - 1 && num != 0) {
				result += s1[num] + s2[n - 2 - i];
			} else {
				result += s1[num];
			}
		}
		return result;

	}

	/**
	 * 构建智能投相关合同所需数据
	 */
	public IntelligentContractDTO buildIntelligenceContractDTO(String userId, ProjectPackageInvestOrder projectPackageInvestOrder) {
		// 构建风险合同数据
		IntelligentContractDTO contractDTO = new IntelligentContractDTO();
		contractDTO.setUserId(userId);
		contractDTO.setContractId(snowflakeIdWorker.nextId() + "");
		contractDTO.setPackageId(projectPackageInvestOrder.getPackageId());
		contractDTO.setPackageInvestOrderId(projectPackageInvestOrder.getId());

		if (projectPackageInvestOrder.getInvestorType() == 1) { //投资人类型(1:个人，2:企业)
			UserIdentityInfoResponseDTO userIdentityInfo = userIdentityDubboService.get(userId);
			if (userIdentityInfo == null) {
				throw new BizException("TRD10005", "智能投相关合同处理异常 userIdentityInfo is null");
			}

			contractDTO.setUserName(userIdentityInfo.getName());
			contractDTO.setIdCard(userIdentityInfo.getIdCard());
			UserAuthorizationInfoResponseDTO userAuthorizationInfo = userAuthorizationInfoDubboService.getUserAuthorizationInfo(userId);
			if (userAuthorizationInfo == null) {
				throw new BizException("TRD10005", "智能投相关合同处理异常 userAuthorizationInfo is null");
			}
			contractDTO.setFadadaCacertId(userAuthorizationInfo.getFadadaCacertId()); // 授权信息(CA证书编号)
		} else { //企业
			SimpleOrgInfo orgInfo = organizationDubboService.getByOrgId(userId);
			if (orgInfo == null) {
				throw new BizException("TRD10005", "智能投相关合同处理异常 orgInfo is null");
			}
			contractDTO.setUserName(orgInfo.getOrganizationName());
			contractDTO.setFadadaCacertId(orgInfo.getFadadaCacertId()); // 法大大证书ID 授权信息(CA证书编号)
		}
		return contractDTO;
	}

	/**
	 * 生成法大大签名时使用的关键字 字符中间用空格隔开，一个合同中只需要签署一个地方时使用
	 * @param originalStr
	 * @return
	 */
	public String getFinalSinNameWithSpace(String originalStr) {
		if (!org.springframework.util.StringUtils.hasText(originalStr)) {
			return "";
		}
		char[] nameChars = originalStr.toCharArray();
		String chanNames = "";
		for (int i = 0; i < nameChars.length; i++) {
			chanNames = chanNames.concat(nameChars[i] + " ");
		}
		chanNames = chanNames.trim();
		return chanNames;
	}

}
